﻿//************************************************************************************************************
// CoNatural.Dto.dll
// Author: Roger Torres
//************************************************************************************************************
// You can use, modify, and distribute the source code and executable programs based on the source code.
// This source code is provided "as is" and without warranties as to performance or merchantability. 
// The author and/or distributors of this source code may have made statements about this source code. 
// Any such statements do not constitute warranties and shall not be relied on by the user in deciding 
// whether to use this source code. This source code is provided without any express or implied warranties 
// whatsoever. Because of the diversity of conditions and hardware under which this source code may be used, 
// no warranty of fitness for a particular purpose is offered. The user is advised to test the source code 
// thoroughly before relying on it. The user must assume the entire risk of using the source code.
//************************************************************************************************************

using System;
using System.Runtime.Serialization;
using System.ComponentModel;
 
namespace CoNatural.Dto {
	/// <summary>
	/// Represents the state of the DTO
	/// </summary>
	public enum DtoState {
		Unchanged = 0,
		Inserted = 1,
		Updated = 2,
		Deleted = 3
	}

	/// <summary>
	/// Implemented by DTOs 
	/// </summary>
	[DataContract(IsReference = true)]
	public abstract class Dto {
		[DataMember]
		public DtoState DtoState { get; set; }

		private bool _changeTracking = false;
		public bool ChangeTracking {
			get { return _changeTracking; }
			set { 
				_changeTracking = value;
				INotifyPropertyChanged iNotify = this as INotifyPropertyChanged;
				if (iNotify != null) {
					if (_changeTracking)
						iNotify.PropertyChanged += OnPropertyChanged;
					else
						iNotify.PropertyChanged -= OnPropertyChanged;
				}
			}
		}

		private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) {
			Dto item = sender as Dto;
			if (item != null && e.PropertyName != "DtoState") {
				if (item.DtoState == DtoState.Unchanged)
					item.DtoState = DtoState.Updated;
			}
		}
	}
}
